<?php
/*
Plugin ID: cn.usephp.cache.file
Plugin Name: File 缓存
Plugin URI: http://www.usephp.cn/plugins/file.html
Description: 使用文件系统为整系统提供缓存功能。
Author: Leo Ning
Version: 1.0
Author URI: http://www.usephp.cn/
*/
class FCachedImpl implements ICache {
	private $cache_dir;
	public function __construct() {
		$this->cache_dir = TMP_PATH . 'cache' . DS;
	}
	/* (non-PHPdoc)
	 * @see ICache::add()
	 */
	public function add($key, $value, $expire = 0, $group = 'default') {
		if ($expire == 0) {
			return false;
		}
		$expire += time ();
		$value = $expire . '<<<<->>>>>' . $value;
		$file = $this->getCacheFile ( $key, $group );
		return @file_put_contents ( $file, $value );
	}
	
	/* (non-PHPdoc)
	 * @see ICache::clear()
	 */
	public function clear($check = true, $group = 'default') {
		
		if (empty ( $group )) {
			$file = $this->cache_dir . $group . DS;
		} else {
			$file = $this->cache_dir;
		}
		if(is_dir($file)){
			return rmdirs ( $file );
		}else{
			return true;
		}
	}
	
	/* (non-PHPdoc)
	 * @see ICache::delete()
	 */
	public function delete($key, $group = 'default') {
		$file = $this->getCacheFile ( $key, $group );
		return @unlink ( $file );
	}
	
	/* (non-PHPdoc)
	 * @see ICache::get()
	 */
	public function get($key, $group = 'default') {
		$file = $this->getCacheFile ( $key, $group );
		if (file_exists ( $file )) {
			$content = file_get_contents ( $file );
			$pos = strpos ( $content, "<<<<->>>>>" );
			if ($pos > 0) {
				$expire = intval ( substr ( $content, 0, $pos ) );
				if ($expire > time ()) {
					return substr ( $content, $pos + 10 );
				}
			}
		}
		return null;
	}
	
	private function getCacheFile($key, $group) {
		$file = $this->cache_dir . $group . DS;
		$key = strlen ( $key ) != 32 ? md5 ( $key ) : $key;
		$d1 = $this->toInt ( substr ( $key, 0, 8 ) );
		$d2 = $this->toInt ( substr ( $key, 8, 8 ) );
		$d3 = $this->toInt ( substr ( $key, 16, 8 ) );
		$d4 = $this->toInt ( substr ( $key, 24, 8 ) );
		$file .= $d1 . DS . $d2 . DS . $d3 . DS . $d4 . DS;
		if (! file_exists ( $file )) {
			mkdir ( $file, 0755, true );
		}
		return $file . $key;
	}
	private function toInt($str) {
		$int = 0;
		for($i = 0; $i < 8; $i ++) {
			$int += ord ( $str {$i} );
		}
		return $int % 256;
	}
}

bind ( 'get_cache_driver', 'create_fcacheimpl_instance', 200 );
function create_fcacheimpl_instance($driver) {
	if (empty ( $driver )) {
		$driver = new FCachedImpl ();
	}
	return $driver;
}